package com.example.voluntary.listener;

import com.example.common.domain.Result;
import com.example.upload.api.UploadClient;
import com.example.voluntary.constants.MQConstants;
import com.example.voluntary.domain.po.VolunteerActivities;
import com.example.voluntary.domain.vo.ActivityDetailVO;
import com.example.voluntary.mapper.VolunteerActivitiesMapper;
import com.example.voluntary.service.VolunteerActivitiesService;
import com.example.voluntary.utils.GenerateQrCodeUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.zxing.WriterException;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.time.Duration;
import java.time.LocalDateTime;

@Component
@RequiredArgsConstructor
public class ActivityDelayListener {
    private final UploadClient uploadClient;
    private final ObjectMapper objectMapper;
    private final VolunteerActivitiesService activityService;
    private final RabbitTemplate rabbitTemplate;
    private final VolunteerActivitiesMapper  volunteerActivitiesMapper;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MQConstants.DELAY_ACTIVITY_QUEUE_NAME),
            exchange = @Exchange(value = MQConstants.DELAY_EXCHANGE_NAME),
            key = MQConstants.DELAY_ACTIVITY_KEY
    ))
    public void listenActivityDelayMessage(Integer activityId) throws IOException, WriterException {
        System.out.println("监听到延迟消息：" + activityId);
        // 生成签到/签退二维码
        BufferedImage qrCode = GenerateQrCodeUtil.getQrCode(activityId);
        try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
            // 使用 png 格式写入图像
            ImageIO.write(qrCode, "png", os);
            byte[] bytes = os.toByteArray();
            String path = "activityQrCode" + "/" + activityId + ".png";
            String result = uploadClient.uploadFiles(bytes, path);
            // 将 JSON 字符串 result 转换成 Result 对象
            Result resultObject = objectMapper.readValue(result, Result.class);
            VolunteerActivities activities = VolunteerActivities.builder()
                    .qrcodeUrl((String) resultObject.getData())
                    .activityId(activityId)
                    .build();
            // 更新活动信息
            volunteerActivitiesMapper.auditVoluntaryActivity(activities);
            ActivityDetailVO activityDetail = activityService.getActivityDetail(activityId);
            // 获取当前时间
            LocalDateTime now = LocalDateTime.now();

            // 获取活动开始招募时间
            LocalDateTime startTimeRecruit = activityDetail.getStartTime();

            // 计算相差的秒数
           /* long secondsUntilStartRecruit = Duration.between(now, startTimeRecruit).getSeconds();
            if (secondsUntilStartRecruit <= 0) {
                // 活动已开始招募，直接修改活动状态
                activities.setStatus(1);
               volunteerActivitiesMapper.updateActivity(activities);
               //计算招募到开始报名时间
                LocalDateTime startTime =activityDetail.getRegistrationStartTime();
                long secondsUntilStart = Duration.between(now, startTime).getSeconds();
                if (secondsUntilStart <= 0) {
                    // 活动已开始报名，直接修改活动状态
                    activities.setStatus(2);
                    volunteerActivitiesMapper.updateActivity(activities);
                } else {
                    // 活动未开始报名，发送消息给 DELAY_START_QUEUE_NAME
                    rabbitTemplate.convertAndSend(MQConstants.ACTIVITY_START_EXCHANGE_NAME, MQConstants.ACTIVITY_START_KEY, activityId, new MessagePostProcessor() {
                        @Override
                        public Message postProcessMessage(Message message) throws AmqpException {
                            message.getMessageProperties().setDelayLong(secondsUntilStart * 1000L);
                            return message;
                        }
                    });
                }

            } else {
                // 活动未开始，发送消息给 DELAY_RECRUIT_QUEUE_NAME
                rabbitTemplate.convertAndSend(MQConstants.ACTIVITY_RECRUIT_EXCHANGE_NAME, MQConstants.ACTIVITY_RECRUIT_KEY, activityId, new MessagePostProcessor() {
                    @Override
                    public Message postProcessMessage(Message message) throws AmqpException {
                        message.getMessageProperties().setDelayLong(secondsUntilStartRecruit * 1000L);
                        return message;
                    }
                });
            }
        }*/
        }
    }


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MQConstants.ACTIVITY_RECRUIT_QUEUE_NAME),
            exchange = @Exchange(value = MQConstants.ACTIVITY_RECRUIT_EXCHANGE_NAME),
            key = MQConstants.ACTIVITY_RECRUIT_KEY
    ))
    public void listenActivityRecruitMessage(Integer activityId) {
        System.out.println("监听到活动开始招募消息：" + activityId);
        VolunteerActivities activities = VolunteerActivities.builder()
                .status(1)
                .build();
        volunteerActivitiesMapper.updateActivity(activities);
        // 计算 recruit 到 start 的时间差
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime startTime = activityService.getActivityDetail(activityId).getRegistrationStartTime();
        long secondsUntilStart = Duration.between(now, startTime).getSeconds();
        if (secondsUntilStart <= 0) {
            // 活动已开始报名，直接修改活动状态
            activities.setStatus(2);
            volunteerActivitiesMapper.updateActivity(activities);
        } else {
            // 活动未开始报名，发送消息给 DELAY_START_QUEUE_NAME
            rabbitTemplate.convertAndSend(MQConstants.ACTIVITY_START_EXCHANGE_NAME, MQConstants.ACTIVITY_START_KEY, activityId, new MessagePostProcessor() {

                @Override
                public Message postProcessMessage(Message message) throws AmqpException {
                    message.getMessageProperties().setDelayLong(secondsUntilStart * 1000L);
                    return message;
                }
            });
        }
    }



    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MQConstants.ACTIVITY_START_QUEUE_NAME),
            exchange = @Exchange(value = MQConstants.ACTIVITY_START_EXCHANGE_NAME),
            key = MQConstants.ACTIVITY_START_KEY
    ))
    public void listenActivityStartMessage(Integer activityId) {
        System.out.println("监听到活动开始报名消息：" + activityId);
        VolunteerActivities activities = VolunteerActivities.builder()
                .status(2)
                .build();
        volunteerActivitiesMapper.updateActivity(activities);
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime endTime = activityService.getActivityDetail(activityId).getEndTime();
        long secondsUntilEnd = Duration.between(now, endTime).getSeconds();
        if (secondsUntilEnd <= 0) {
            // 活动已结束，直接修改活动状态
            activities.setStatus(3);
            volunteerActivitiesMapper.updateActivity(activities);
        } else {
            // 活动未结束，发送消息给 DELAY_END_QUEUE_NAME
            rabbitTemplate.convertAndSend(MQConstants.ACTIVITY_END_EXCHANGE_NAME, MQConstants.ACTIVITY_END_KEY, activityId, new MessagePostProcessor() {
                @Override
                public Message postProcessMessage(Message message) throws AmqpException {
                    message.getMessageProperties().setDelayLong(secondsUntilEnd * 1000L);
                    return message;
                }
            });
        }
    }
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MQConstants.ACTIVITY_END_QUEUE_NAME),
            exchange = @Exchange(value = MQConstants.ACTIVITY_END_EXCHANGE_NAME),
            key = MQConstants.ACTIVITY_END_KEY
    ))
    public void listenActivityEndMessage(Integer activityId) {
        System.out.println("监听到活动结束消息：" + activityId);
        VolunteerActivities activities = VolunteerActivities.builder()
                .status(3)
                .build();
        volunteerActivitiesMapper.updateActivity(activities);
    }
}
